package main

import (
	"apiserver/config"
	"apiserver/model"
	v "apiserver/pkg/version"
	"apiserver/router"
	"apiserver/router/middleware"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/lexkong/log"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"net/http"
	"os"
	"time"
)

var (
	cfg = pflag.StringP("config", "c", "", "apiserver config file path.")
)

var (
	version = pflag.BoolP("version", "v", false, "show version info.")
)

func main() {
	pflag.Parse()

	if *version {
		v := v.Get()
		marshalled, err := json.MarshalIndent(&v, "", "  ")
		if err != nil {
			fmt.Printf("%v\n", err)
			os.Exit(1)
		}

		fmt.Println(string(marshalled))
		return
	}

	// 初始化配置
	if err := config.Init(*cfg); err != nil {
		panic(err)
	}

	// 初始化数据库配置
	model.DB.Init()
	defer model.DB.Close()

	// 设置gin的运行模式
	gin.SetMode(viper.GetString("runmode"))

	// 创建gin的服务
	g := gin.New()

	// 加载路由
	router.Load(g, middleware.RequestId(), middleware.Logging())

	go func() {
		if err := pingServer(); err != nil {
			log.Fatal("路由器没有响应，或者可能需要很长时间才能启动", err)
		}
		log.Info("路由器已成功部署")
	}()

	addr := viper.GetString("addr")

	log.Infof("服务器已启动开始监听端口: %s", addr)
	log.Info(http.ListenAndServe(addr, g).Error())
}

// pingServer ping http服务器以确保路由器工作正常
func pingServer() error {
	for i := 0; i < viper.GetInt("max_ping_count"); i++ {
		resp, err := http.Get(viper.GetString("url") + "/sd/health")
		if err == nil && resp.StatusCode == 200 {
			return nil
		}
		log.Info("等待路由器，1秒后重试")
		time.Sleep(time.Second)
	}
	return errors.New("无法连接到路由器")
}
